import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

let loadingInstance = null

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE || '',
  timeout: 10000
})

// 请求拦截器，自动携带 token，并显示 loading
service.interceptors.request.use(
  config => {
    loadingInstance = ElLoading.service({ fullscreen: true, text: '加载中...' })
    const token = localStorage.getItem('token')
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
  },
  error => {
    if (loadingInstance) loadingInstance.close()
    return Promise.reject(error)
  }
)

// 响应拦截器，关闭 loading
service.interceptors.response.use(
  res => {
    if (loadingInstance) loadingInstance.close()
    if (res.data && res.data.code !== 200) {
      ElMessage.error(res.data.message || '请求失败')
      return Promise.reject(res.data)
    }
    return res.data
  },
  err => {
    if (loadingInstance) loadingInstance.close()
    ElMessage.error(err.message || '网络错误')
    return Promise.reject(err)
  }
)

// 只导出 post 方法
export function post(url, data, config = {}) {
  return service.post(url, data, config)
}

export function get(url, params, config = {}) {
  return service.get(url, { params, ...config })
}

export function put(url, data, config = {}) {
  return service.put(url, data, config)
}

export function del(url, config = {}) {
  return service.delete(url, config)
}

export default service 